package tech.cn.note.word.fun;

import java.text.DecimalFormat;

import com.deepoove.poi.render.compute.RenderDataCompute;

import org.springframework.stereotype.Service;

import static org.springframework.util.ObjectUtils.isEmpty;

@Service
public class Percent implements RenderFunction {
    /**
     * @param fields            参数 1 数字 参数2 可选  小数保留位数
     * @param renderDataCompute
     * @return
     */
    @Override
    public String doCalculate(String[] fields, RenderDataCompute renderDataCompute) {
        if (isEmpty(fields)) {
            return "";
        }
        int pointNum = 4;
        if (fields != null && fields.length > 1) {
            pointNum = Integer.parseInt(fields[1]);
        }
        DecimalFormat decimalFormat = buildNumberFormat(pointNum);
        Object compute = renderDataCompute.compute(fields[0]);
        if (compute == null) {
            return "";
        }
        return decimalFormat.format(compute);
    }

    /**
     * 获取转换定义对象
     *
     * @param pointNum
     * @return
     */
    public DecimalFormat buildNumberFormat(int pointNum) {
        return new DecimalFormat(getFormatDefinition(pointNum));
    }

    /**
     * 获取转换定义格式
     *
     * @param pointNum
     * @return
     */
    public String getFormatDefinition(int pointNum) {
        StringBuffer strDefinition = new StringBuffer(getDefaultDefinition());
        if (pointNum < 1) {
            return strDefinition.toString();
        }
        strDefinition.append(".");
        for (int i = 0; i < pointNum; i++) {
            strDefinition.append("0");
        }
        return strDefinition.append("%").toString();
    }

    /**
     * 获取默认的转换定义格式
     *
     * @return
     */
    public String getDefaultDefinition() {
        return "0";
    }
}
